package lesson02;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;

public class Demo_208 {


    public static void main(String[] Sargs) throws IOException {
        //1.输入一个目录
        System.out.println("请输入要扫描的路径:");
        Scanner scanner = new Scanner(System.in);
        File rootFile = new File(scanner.next());
        //2.验证目录是否存在
        if (!rootFile.exists()) {
            System.out.println("路径不存在");
            return;
        }

        if (!rootFile.isDirectory()) {
            System.out.println("你输入的路径不是一个目录");
            return;
        }

        //3.输入指定普通文件名
        System.out.println("请输入查询的字符串:");
        String keyword = scanner.next();
        if (keyword == null || keyword.isEmpty()) {
            return;
        }
        scan(rootFile, keyword);


    }

    private static void scan(File rootPath, String keyword) throws IOException {
        File[] files = rootPath.listFiles();

        if (files.length == 0) {
            return;
        }

        for (File file : files) {
            if (file.isFile()) {
                String fileName = file.getName();

                if (fileName.contains(keyword)) {
                    System.out.println("找到文件" + file.getCanonicalPath() +
                            ",包含关键字" + keyword + ",是否删除(Y/N)");
                    Scanner scanner =new Scanner(System.in);
                    String next= scanner.next();
                    if (next.toLowerCase().equals("y")){
                        file.delete();
                        System.out.println("删除文件"+file.getCanonicalPath()+"成功");
                    }
                }


            } else {
                scan(file, keyword);
            }
        }

    }
}
